package me.zhanshi123.lab4.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import me.zhanshi123.lab4.entity.AuthIdentity;
import me.zhanshi123.lab4.entity.User;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

@Service
public class JwtUtils {

    private final String SUBJECT = "goodMgr";
    private final Key KEY = Keys.hmacShaKeyFor(Decoders.BASE64.decode("SECRETHERESECRETHERESECRETHERESECRETHERESECRETHERESECRETHERESECRETHERESECRETHERE"));
    private final JwtParser JWT_PARSER = Jwts.parserBuilder()
            .requireSubject(SUBJECT)
            .setSigningKey(KEY)
            .build();

    public String createJwt(User user, long expire) {
        Date expireDate = new Date();
        expireDate.setTime(System.currentTimeMillis() + expire);

        return Jwts.builder()
                .setIssuedAt(new Date())
                .setSubject(SUBJECT)
                .claim("user", user.getName())
                .claim("group", user.getGroup())
                .setExpiration(expireDate)
                .signWith(KEY)
                .compact();
    }

    public AuthIdentity validateUser(String token) {
        try {
            Claims claims = JWT_PARSER.parseClaimsJws(token)
                    .getBody();
            if (claims.getExpiration().before(new Date())) {
                return null;
            }
            return new AuthIdentity(claims.get("user", String.class), claims.get("group", Integer.class));
        } catch (Exception e) {
            return null;
        }
    }
}
